package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import domain.User;
import domain.util.HibernateFactory;

public class UserDAO {

	SessionFactory fact = HibernateFactory.getSessionFactory();
	Session session = fact.openSession();
	Transaction t = null;

	@SuppressWarnings("unchecked")
	public User getUser(String login) {
		List<User> lista = session.createQuery(
				"from domain.User where login = '" + login + "'").list();
		if (lista.isEmpty())
			return null;
		return lista.get(0);
	}

	public boolean saveOrUpdate(User user) {
		try {
			t = session.beginTransaction();
			session.saveOrUpdate(user);
			t.commit();
			return true;
		} catch (Exception e) {
			t.rollback();
			return false;
		}

	}

	public List<User> listUser() {
		List<User> users = null;
		try {
			users = session.createQuery("FROM domain.User ORDER BY name").list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

	public User listUserById(Long userId) {
		User user = null;
		try {
			user = (User) session.get(User.class, userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	public List<String> getUserNames(String name) {
		List<String> list = session.createQuery(
				"SELECT u.name FROM domain.User u WHERE u.name LIKE ('" + name
						+ "%') ORDER BY u.name").list();
		return list;
	}

	public void deleteUser(long userId) {
		try {
			t = session.beginTransaction();
			User user = (User) session.get(User.class, userId);
			session.delete(user);
			
		} catch (Exception e) {
			t.rollback();
			e.printStackTrace();
		}
	}

}
